<?php
/**
 * 购物车控制器congcong
 */
namespace Home\Controller;
use Think\Controller;
class CartController extends Controller{
    /**
     * 购物车列表
     */
    public function index()
    { 
      $where['a.uid']=!empty($_SESSION['uid'])?$_SESSION['uid']:0;
      $page=I('get.page',1,'strip_tags');
      $count=M('shipping_cart a')->join("cart_item b on a.itemid=b.itemid")->where($where)->count();
      $pagearr=getPageArr($page,C('PAGESIZE'),$count);
      $res=M('shipping_cart a')->join("cart_item b on a.itemid=b.itemid")
                               ->where($where)->order("addtime")
                               ->limit($pagearr['start'],$pagearr['pagesize'])
                               ->Field("a.itemid,a.itemname,a.productid,a.number,a.price,a.addtime,b.itemimg,a.totalprice,a.speci,a.id,b.bn")
                               ->select();

      foreach($res as $k=>$v)
      {
         $total+=$v['totalprice'];/////所有商品总价
          $totalnum+=$v['number'];////所有商品数量
        if(empty($v['productid']))
        {
         $res[$k]['inventory']=M('item')->where("itemid='%d'",$v['itemid'])->getField("inventory");
       }else{
        $res[$k]['inventory']=M('product')->where("productid='%d' and itemid='%d'",$v['productid'],$v['itemid'])->getField("inventory");
      }

    }

    $this->assign('res',$res)->assign('pagearr',$pagearr)->assign('total',$total)->assign("totalnum",$totalnum);
    

    $this->display();
  }
    /**
     * 更改购物车数量
     */
    public function ajaxnum()
    {
      $where['id']  =I('get.id','','strip_tags');
      $number=I('get.shu','','strip_tags');
      $data['number']=$number;
      $price=I('get.price','','strip_tags');
      $data['totalprice']=$number*$price;
      $re=M('shipping_cart')->where($where)->data($data)->save();
      if($re!==false){
       echo '1';
     }else
     {
       echo '2';
     }
   }
    /**
     * 删除购物车
     */
    public function ajaxdel()
    {   
      $id=I('post.id','','strip_tags');
      $where['id']=array("in",$id);
      $res=M('shipping_cart')->where($where)->delete();

      if($res!==false){
        echo '1';
      }else{
        echo '2';
      }
    }
    /*
     *加入购物车
     *@param itemid (int)  , productid (int) ,number(int)
     *return  json  
     *@author fan  
    */    
    public function addCart()
    {
        $result='';
        $itemid=I('post.itemid',0,'strip_tags');
        $productid=I('post.productid',0,'strip_tags');
        $number=I('post.itemnumber',0,'strip_tags');
        $uid=!empty($_SESSION['uid'])?$_SESSION['uid']:0;
        //判断用户是否登录
        if(empty($uid))
        {
          $result['status']=3;
          $result['msg']='只有登录的用户才能使用购物车';
          echo json_encode($result);
          return '';
        }
        if(empty($itemid) || empty($number)) 
        {
            $result['status']=0;
            $result['msg']='参数错误,请选择商品或者数量';
            echo  json_encode($result);
            return '';
        }
        //判断此商品是否存在购物车中
        $cart=M('shipping_cart');
        $cid=$cart->where('itemid=%d AND productid=%d AND uid=%d',$itemid,$productid,$uid)->getField('id');
        //此商品存在购物车中，更新数量及商品总价
        if(!empty($cid))
        {
          $where['id']=$cid;
          $temp=$cart->where($where)->getField('id,number,totalprice,price');
          $cart->create();
          $cart->number=$number+intval($temp[$cid]['number']);
          $cart->totalprice=($number*intval($temp[$cid]['price']))+$temp[$cid]['totalprice'];
          $cart->where($where)->save();
          $carttotal=$cart->where('uid=%d',$uid)->sum('number');
          $result['status']=($carttotal !==false)?1:0;
          $result['carttotal']=($carttotal !==false)?$carttotal:0;
          $result['msg']=($carttotal !==false)?'':'系统繁忙，请稍后再试';
          echo json_encode($result);
          return '';
        }
        //商品不存在购物车中,判断此商品是否为货品
        $cart->create();
        if(!empty($productid))
        {
          $productid=intval($productid);
          $temp1=M()->query('select price,color from '.C('DB_PREFIX').'product where productid='.$productid);
          $cart->price=$temp1[0]['price'];
          $cart->speci=$temp1[0]['color'];
          $cart->totalprice=$number*intval($temp1[0]['price']);
        }else{
           $price=M('item')->where('itemid=%d',$itemid)->getField('price');
           $cart->price=$price;
           $cart->totalprice=intval($price)*$number;
        }
        //获取商品基本信息
        $iteminfo=M('item')->where('itemid=%d',$itemid)->getField('itemid,itemname,itemimg,bn');
        $cart->itemname=$iteminfo[$itemid]['itemname'];
        $cart->imgurl=$iteminfo[$itemid]['itemimg'];
        $cart->bn=$iteminfo[$itemid]['bn'];
        $cart->addtime=time();
        $cart->itemid=$itemid;
        $cart->productid=$productid;
        $cart->number=$number;
        $cart->uid=$uid;
        $temp2=$cart->add();
        //计算购物车商品总数量
        if($temp2 !==false)
        {
            $carttotal=$cart->where('uid=%d',$uid)->sum('number');
            $result['status']=($carttotal !==false)?1:0;
            $result['msg']=($carttotal !==false)?'':'系统繁忙，请稍后再试';
            $result['carttotal']=($carttotal !==false)?$carttotal:0;
            echo json_encode($result);
            return '';
        }

        $result['status']=0;
        $result['msg']='系统繁忙，请稍后再试';
        echo json_encode($result);
        return '';
        

    }
    /**
     * 计算选中商品的总价
     */
    public function Total()
    {
     $id=I('post.id','','strip_tags');

     $where['id']=array("in",$id);
     $res=M('shipping_cart')->where($where)->Field("totalprice,number")->select();
     foreach($res as $k=>$v)
     {
      $num+=$v['number'];
      $totalprice+=$v['totalprice'];
    }
    $re['num']=intval($num);
    $re['totalprice']=$totalprice;
    echo json_encode($re,JSON_UNESCAPED_UNICODE);
  }

}